package com.ruisoft.business.salary.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruisoft.base.controller.BaseController;
import com.ruisoft.base.dao.BaseDao;
import com.ruisoft.business.employee.service.EmployeeService;
import com.ruisoft.business.exportExcel.util.ExcelUtil;
import com.ruisoft.business.salary.ExcelReader;
import com.ruisoft.business.salary.service.SalaryService;
import com.ruisoft.common.CommonUtil;
import com.ruisoft.core.json.JSONMap;
import com.ruisoft.core.param.RequestUtil;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * @author LJQ
 *
 */

@Controller
@RequestMapping("/salary/")
public class SalaryController extends BaseController {

	private static final Logger LOG = Logger.getLogger(SalaryController.class);

	@Autowired
	private SalaryService salaryService;
	
	@Autowired
	private BaseDao baseDao;
	
	@Autowired
	private EmployeeService employeeService;
	
	/**
	 * 查询员工工资信息
	 */
	@RequestMapping("query")
	public void query() {
		JSONMap<String, Object> json = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
		if (queryData == null)
			queryData = getQueryData();
		try {
			List<JSONObject> result = salaryService.searchForPage(queryData);
			queryResponse(queryData, result);
		} catch (Exception e) {
			LOG.error("查询工资信息发生错误", e);
			json.put("status", "-2");
			json.put("msg", "执行查询工资信息操作发生错误");
		} finally {
			try {
				response(json);
			} catch (IOException e) {
				LOG.error("查询返回信息时发生错误", e);
			}
			queryData = null;
		}
	}

	/**
	 * 新增员工工资信息
	 */
	@RequestMapping("saveSalary")
	public void saveSalary() {
		JSONMap<String, Object> json = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
		try {
			JSONObject reqData = getReqData();
			JSONObject result = new JSONObject();
			result = salaryService.saveSalary(reqData);
			json.put("added", result);
			json.put("status", "1");
		} catch (Exception e) {
			LOG.error("保存工资信息发生错误", e);
			json.put("status", "-2");
			json.put("msg", "保存工资信息发生错误");
		} finally {
			try {
				response(json);
			} catch (IOException e) {
				LOG.error("返回信息时发生错误", e);
			}
		}
	}
	
	/**
	 * 查询单个员工的工资信息
	 * @param salaryid 工资编号
	 */
	@RequestMapping("searchSalary/{salaryid}")
	public void searchUser(@PathVariable String salaryid) {
		JSONMap<String, Object> json = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
		try{
			JSONObject result = salaryService.searchSalary(salaryid);
			json.put("data", result);
			json.put("status", 1);
		} catch (Exception e) {
			LOG.error("查询员工工资信息发生错误", e);
			json.put("status", "-2");
			json.put("msg", "执行查询员工工资信息操作发生错误");
		} finally {
			try {
				response(json);
			} catch (IOException e) {
				LOG.error("查询返回信息时发生错误", e);
			}
		}
	}
	
	/**
	 * 修改员工工资信息
	 */
	 @RequestMapping("updateSalary")
   public void updateSalary() {
       JSONMap<String, Object> json = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
       try {
           JSONObject reqData = getReqData();
           JSONObject result = new JSONObject();
           result = salaryService.updateSalary(reqData);
           json.put("data", result);
           json.put("status", "1");
       } catch (Exception e) {
           LOG.error("更新员工工资信息发生错误", e);
           json.put("status", "-2");
           json.put("msg", "更新员工工资信息发生错误");
       } finally {
           try {
               response(json);
           } catch (IOException e) {
               LOG.error("返回信息时发生错误", e);
           }
       }
   }
	
	/**
	 * 删除员工工资信息
	 * @param id
	 * @throws Exception
	 */
	@RequestMapping("deleteSalary/{id}")
    public void deleteSalary(@PathVariable String id) throws Exception{
        int status = salaryService.deleteSalary(id);
        JSONMap<String, Object> json = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
        json.put("status", status);
        response(json);
    }
	
	@RequestMapping("exportSalary")
    public String exportSalary(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
		String fileName="员工工资";
        String columnNames[]={"姓名","工号","工资月份","基本薪资","加班补贴","缺勤扣款","五险一金扣款","考勤天数","考勤异常天数","实发工资","状态"};//列名
        String keys[] = {"username","userid","sal_date","base_wage","allowance","absence_deduct","insurance","attendance_day","atten_abnormal_day","actual_salary","sal_state"};//map中的key
        if (queryData == null)
			queryData = getQueryData();
        List<JSONObject> result = baseDao.query(new JSONObject(data), "salary.select.salaryinfo.query");
        List<Map<String,Object>> list=createExcelRecord(result,keys);
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }
	
	 private List<Map<String, Object>> createExcelRecord(List<JSONObject> result, String[] keys) {
         List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("sheetName", "sheet1");
         listmap.add(map);
         for (int i = 0; i < result.size(); i++) {
        	 JSONObject obj = result.get(i);
        	 Map<String, Object> mapValue = new HashMap<String, Object>();
        	 for(int j = 0; j<keys.length; j++) {
        		 if("sal_state".equals(keys[j])) {
        			 if("1".equals(obj.get(keys[j]))) {
        				 mapValue.put(keys[j], "有效");
        			 } else if("2".equals(obj.get(keys[j]))) {
        				 mapValue.put(keys[j], "无效");
        			 }
        		 } else{
        			 mapValue.put(keys[j], obj.get(keys[j]));
        		 }
        		 
        	 }
        	 listmap.add(mapValue);
         }
         return listmap;
     }
	 
	 
	 
	 
	 /**
	  * 导入Excel
	  * @param request
	  * @param response
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("salaryExcelUpload")
	    public String salaryExcelUpload(HttpServletRequest request,HttpServletResponse response) throws Exception {
			JSONMap<String, Object> json = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
			JSONObject result = new JSONObject();
			String str="";
			try {
				String url = request.getSession().getServletContext().getRealPath("\\");
				url=url+File.separator+"upload";
			    String excelFilePath = uploadFile(url);
			    System.out.println("------------excelFilePath::::::::::"+ excelFilePath);
			    ExcelReader excel = new ExcelReader(excelFilePath);
			    List dataList = excel.getAllData(0);
			    if(dataList.size()>0 && dataList !=null) {
			    	for(int i=1; i<dataList.size(); i++) {
			    		JSONObject obj =new JSONObject();
				    	String[] row = (String[]) dataList.get(i);
				    	String userid = row[1];
				    	JSONObject empObj = employeeService.searchUser(userid,request);
				    	obj.put("userid", userid);
				    	obj.put("company_id", empObj.get("company_id"));
				    	obj.put("dept_id", empObj.get("dept_id"));
				    	obj.put("sal_date", row[2]);
				    	obj.put("base_wage", row[3]);
				    	obj.put("allowance", row[4]);
				    	obj.put("absence_deduct", row[5]);
				    	obj.put("insurance", row[6]);
				    	obj.put("actual_salary", row[9]);
				    	obj.put("attendance_day", row[7]);
				    	obj.put("atten_abnormal_day", row[8]);
				    	obj.put("sal_note", "");
				    	obj.put("write_uid", RequestUtil.getCurrentUserAccount());
				    	obj.put("write_date", CommonUtil.getCurDateTime());
				    	obj.put("audit_uid", RequestUtil.getCurrentUserAccount());
				    	obj.put("audit_date", CommonUtil.getCurDateTime());
				    	result = salaryService.saveSalary(obj);
				    }
			    }
			    str="导入excel成功！";
			} catch (Exception e) {
				LOG.error("导入excel发生错误", e);
				str="导入excel失败！";
			} 
			return str;
	 }
	 
	 /**
	  * 导入Excel
	  * @param request
	  * @param response
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("downloadSalaryTemp")
	    public String downloadSalaryTemp(HttpServletRequest request,HttpServletResponse response) throws Exception {
		 	String url = request.getSession().getServletContext().getRealPath("\\")+"download";
		 	String filename = "XXXX年XX月工资表模板.xls";
		 	String filePath = url + File.separator + filename;
		 	File file = new File(filePath);  //根据文件路径获得File文件
		 	response.setContentType("application/vnd.ms-excel;charset=utf-8");
		 	response.setHeader("Content-Disposition", "attachment;filename=\""
		            + new String(filename.getBytes(), "ISO8859-1") + "\"");
		 	response.setContentLength((int) file.length());
		 	byte[] buffer = new byte[2048];// 缓冲区
	        BufferedOutputStream output = null;
	        BufferedInputStream input = null;
	        try {
	            output = new BufferedOutputStream(response.getOutputStream());
	            input = new BufferedInputStream(new FileInputStream(file));
	            int n = -1;
	            //遍历，开始下载
	            while ((n = input.read(buffer, 0, buffer.length)) > -1) {
	               output.write(buffer, 0, n);
	            }
	            output.flush();   //不可少
	            response.flushBuffer();//不可少
	          } catch (Exception e) {
	            //异常自己捕捉       
	          } finally {
	             //关闭流，不可少
	             if (input != null)
	                  input.close();
	             if (output != null)
	                  output.close();
	          }
			return null;
	 }
	 
	 
	 
}
